package com.airui.dao;

import com.airui.domain.User;
import com.airui.utils.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;

public class UserDao {
    QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
    String sql;
    String sql2;

    public int dengLuXiTong(User user) {
        sql = "select id from user where username = ?";
        sql2 = "select id from user where username = ? and password = ?";
        Object params = user.getUsername();
        Object[] params2 = {user.getUsername(), user.getPassword()};
        try {
            if (qr.query(sql2, new ScalarHandler<>(), params2) != null){
                return 2;
            }else if (qr.query(sql, new ScalarHandler<>(), params) != null){
                return 1;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public int zhuCe(User user) {
        sql = "insert into user values(null, ?, ?)";
        sql2 = "select id from user where username = ?";
        Object params2 = user.getUsername();
        Object[] params = {user.getUsername(), user.getPassword()};
        try {
            if (qr.query(sql2, new ScalarHandler<>(), params2) == null){
                return qr.update(sql, params);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public int xiugaiPassword(User user) {
        sql = "select id from user where username = ?";
        sql2 = "update user set password = ? where username = ?";
        Object params = user.getUsername();
        Object[] params2 = {user.getPassword(), user.getUsername()};
        try {
            if (qr.query(sql, new ScalarHandler<>(), params) != null){
                return qr.update(sql2, params2);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
